package com.yy.controller;

import com.yy.entity.PricingStandard;
import com.yy.service.PricingStandardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/pricing")
public class PricingStandardController {
    PricingStandardService service;

    @Autowired
    public PricingStandardController(PricingStandardService service) {
        this.service = service;
    }

    @RequestMapping("/list")
    public String list(Model model) {
        List<PricingStandard> list = service.getAll();
        model.addAttribute("list", list);//model打包成list属性完成list对象的值传递
        return "/pricing/list";
    }

    @RequestMapping(value = "/insert")
    public String insert(Model model) {
        model.addAttribute("pricing", new PricingStandard());
        return "/pricing/edit";
    }

    @RequestMapping(value = "/edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model) {
        PricingStandard entity = service.getById(id);
        model.addAttribute("pricing", entity);
        return "/pricing/edit";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@ModelAttribute("pricing") PricingStandard entity) {
        int result = entity.getId() != null ? service.update(entity) : service.insert(entity);
        // 以下return实现需要对result进行判断,当result为非0,页面跳转到list，否则......
        return "redirect:/pricing/list";
    }


    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id") Long id, Model model) {
        PricingStandard entity = service.getById(id);
        model.addAttribute("pricing", entity);
        return "pricing/detail";

    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        Optional.ofNullable(id)
                .ifPresent(s->{
                    service.delete(id);
                });
        return "redirect:/pricing/list";
    }
}